﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Newtonsoft.Json;
using Model;

namespace Business
{
    public class BPostOrder
    {

        public bool PushOrder(List<Deli_Order> lstDeli_Order)
        {
            RabbitMQConfig _RabbitMQConfig = RabbitMQConfig.Value;
            var factory = new ConnectionFactory()
            {
                HostName = _RabbitMQConfig.HostName,
                UserName = _RabbitMQConfig.UserName,
                Password = _RabbitMQConfig.Password
            };

            string exchange = _RabbitMQConfig.exchange;// "OrderPost";
            string exchangeType = _RabbitMQConfig.exchangeType;// "fanout";//广播式交换器类型
            string routingKey = _RabbitMQConfig.routingKey;// "";
            string queuename = _RabbitMQConfig.queuename;
            DateTime excuteTime = DateTime.Now;
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    if (exchangeType != null)
                    {
                        channel.ExchangeDeclare(exchange, exchangeType, true);//保持交换器持久化
                        channel.QueueDeclare(queuename, true, false, false, null);
                        channel.QueueBind(queuename, exchange, routingKey);
                    }
                    //var orderList = JsonConvert.DeserializeObject<List<Deli_Order>>(json);
                    foreach (var order in lstDeli_Order)
                    {
                        try
                        {
                            string message = JsonConvert.SerializeObject(order);
                            var properties = channel.CreateBasicProperties();
                            properties.DeliveryMode = 2;//保证消息持久化

                            var body = Encoding.UTF8.GetBytes(message);
                            channel.BasicPublish(exchange, "", properties, body);
                            string mes = string.Format("已成功发送订单{0}", order.OrderNo) + Environment.NewLine;
                            LogManager.WriteInfoEventLog(mes);
                        }
                        catch (Exception ex)
                        {
                            LogManager.WriteInfoEventLog(string.Format("发送订单{0}失败：{1}", order.OrderNo, ex.Message) + Environment.NewLine);
                            return false;
                        }
                    }
                }
            }
            return true;
            //int DeleteCount = new OrderBase().DeleteTempOrderInfo(excuteTime);
        }
    }
}
